const Router=require('koa-router')
let router=new Router()

router.get('/updateNickname',async ctx=>{
  let token=ctx.header.token
  let nickname=ctx.query.nickname
  let user=await ctx.db.query('select * from user where token=?',[token])
  if(user.length==0){
    ctx.body={err:1,msg:"账号已在异地登录"}
  }else{
    await ctx.db.query('update user set nickname=? where token=?',[nickname,token])
    user[0].nickname=nickname
    ctx.body={
      err:0,
      data:user
    }
  }
})

router.get('/updateBirthday',async ctx=>{
  let token=ctx.header.token
  let birthday=ctx.query.birthday
  let user=await ctx.db.query('select * from user where token=?',[token])
  if(user.length==0){
    ctx.body={err:1,msg:"账号已在异地登录"}
  }else{
    await ctx.db.query('update user set birthday=? where token=?',[birthday,token])
    user[0].birthday=birthday
    ctx.body={
      err:0,
      data:user
    }
  }
})

router.get('/updateSex',async ctx=>{
  let token=ctx.header.token
  let sex=ctx.query.sex || "-1"
  let user=await ctx.db.query('select * from user where token=?',[token])
  if(user.length==0){
    ctx.body={err:1,msg:"账号已在异地登录"}
  }else{
    await ctx.db.query('update user set sex=? where token=?',[sex,token])
    user[0].sex=sex
    ctx.body={
      err:0,
      data:user
    }
  }
})

router.post('/uploadFace',async ctx=>{
  let token=ctx.header.token
  let path=ctx.request.fields.img[0].path
  let str=path.split('upload_')[1]
  path=root+'/upload/upload_'+str
  console.log(path)
  let user=await ctx.db.query('select * from user where token=?',[token])
  if(user.length==0){
    await ctx.unlink(path)
    ctx.body={err:1,msg:"账号已在异地登录"}
  }else{
    let unlinkUrl=Path.join(__dirname,'../static'+user[0].faceImg.split(root)[1])
    console.log(unlinkUrl)
    await ctx.unlink(unlinkUrl)
    await ctx.db.query('update user set faceImg=? where token=?',[path,token])
    let data=await ctx.db.query('select * from user where token=?',[token])
    ctx.body={
      err:0,
      data
    }
  }
})


module.exports=router